<template>

  <IndexHeader :scroll-trans="false"></IndexHeader>
  <div class="video-play-view">

    <div class="video-play-view-left-container">
      <div class="video-title">
        <h1>{{videoTitle}}</h1>
        <div class="video-sub-title">
<!--          播放-->
          <div class="video-sub-title-item">
            <i class="iconfont icon-bofangshu"></i>
            0
          </div>
<!--          弹幕-->
          <div class="video-sub-title-item">
            <i class="iconfont icon-danmushu"></i>
            0
          </div>
<!--          时间-->
          <div class="video-sub-title-item">
            <i class="iconfont icon-lishijilu"></i>
            {{videoUploadTime?videoUploadTime.format('YYYY-MM-DD HH:mm:ss'):0}}
          </div>

        </div>
      </div>
      <!-- 视频播放器 -->
      <div class="video-player">
        <video ref="videoPlayer" id="my-video" class="video-js vjs-default-skin" controls preload="auto"></video>
      </div>
      <!--点赞收藏-->
      <div class="tool-bar">
        <div class="tool-bar-item" :class="{ 'liked': videoLiked }" @click="toogleVideoLike">
          <i class="iconfont icon-zan"></i>
          {{videoLikeNum}}
        </div>
        <div class="tool-bar-item" :class="{ 'liked': videoFavorited.length }" @click="toogleVideoFavorite">
          <i class="iconfont icon-shoucang"></i>
          {{videoFavoriteNum}}
        </div>
      </div>

      <el-divider v-if="videoTags || videoIntro" direction="horizontal" r></el-divider>
      <!--视频简介-->
      <div class="video-intro">
        {{videoIntro}}
      </div>
      <!--视频标签-->
      <div class="video-tags-box" v-if="videoTags">
        <el-tag type="info" class="video-tag" round v-for="tag in videoTags">{{tag}}</el-tag>
      </div>

      <el-divider direction="horizontal" r></el-divider>

      <!-- 视频信息 -->
      <div class="video-info">
        <p>{{ videoDescription }}</p>
      </div>

      <!-- 评论区 -->
      <div class="comment-section">
        <div class="nav-bar">
          <div class="title">
            <h3>评论</h3>
            <span>{{videoCommentCount}}</span>
          </div>
<!--          <el-radio-group v-model="commentListType" size="small" style="margin-left: 10px;"> >-->
<!--            <el-radio-button label="最热" value="hotest" border="false"/>-->
<!--            <el-radio-button label="最新" value="newest" border="false"/>-->
<!--          </el-radio-group>-->
        </div>
        <!-- 评论输入框 -->
        <div class="comment-input-section">
          <div class="user-avatar">
            <UserAvatar></UserAvatar>
          </div>
          <el-input
              :disabled="!User.isLogin()"
              :rows="4"
              :placeholder="User.isLogin()?'请输入你的评论':'登录后发表评论'"
              class="comment-input"
              v-model="newComment"
              resize="none"
          >
          </el-input>
        </div>

        <div class="comment-submit-btn" v-if="User.isLogin()">
          <el-button type="primary" @click="submitComment">发表评论</el-button>
        </div>


        <!-- 评论列表 -->
        <div v-infinite-scroll="handleInfiniteScroll" :infinite-scroll-disabled="pageNum>=pageTotalNum || totalNum <=1 ">
          <div class="comment-item">
            <FirstLevelComment
                v-for="(comment, index) in comments"
                :key="index"
                :comment-id="comment.id"
                :userId="comment.user_id"
                :time="comment.time"
                :content="comment.comment_content"
                :likeNum="comment.likeNum"
            />
            <div class="none-comment-content">{{User.isLogin()?'没有更多评论':'登录后查看评论'}}</div>
          </div>

        </div>
      </div>
    </div>

    <div class="video-play-view-right-container">
      <div class="user-info-section">
        <UserAvatar class="user-avatar">

        </UserAvatar>
        <div class="user-info">
          <div class="user-name">
            用户{{ userInfo.userid }}
          </div>
          <div class="user-intro">
            用户没有简介
          </div>
          <div class="actionBtn-section">
            <el-button v-if="isFollow" class="followBtn" type="info" @click="toggleFollow">
              <el-icon><Finished /></el-icon>
              已关注
            </el-button>
            <el-button v-else class="followBtn" type="primary" @click="toggleFollow">
              <el-icon><Plus /></el-icon>
              关注
            </el-button>
          </div>

        </div>
      </div>
      <div class="recommendVideoSection">
        <div class="recommend-video-box" v-for="video in recommendVideos">
          <horizon-video-card
              :video="video">
          </horizon-video-card>
        </div>
      </div>
    </div>



  </div>

  <!-- 收藏夹弹窗 -->
  <el-dialog v-model="showFavoritePopup" title="添加到收藏夹" width="30%" @close="closePopup">
    <el-radio-group v-model="selectedCategory" class="category-list">
      <el-radio v-for="category in categories" :key="category" :label="category" class="category-item">
        {{ category }}
      </el-radio>
    </el-radio-group>
    <!-- 新增收藏夹分类 -->
    <div class="add-category">
      <el-button type="text" @click="toggleAddCategory">{{ addCategoryButtonText }}</el-button>
      <el-input
          v-if="isAddingCategory"
          v-model="newCategory"
          placeholder="请输入新的分类名称"
          @keyup.enter="addCategory"
          ref="newCategoryInput"
      >
        <template #append>
          <el-button @click="addCategory">添加</el-button>
        </template>
      </el-input>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="addToFavorites">确定</el-button>
    </div>
  </el-dialog>

</template>

<script setup>
import {onActivated, reactive, ref, nextTick, onMounted, watch} from 'vue';
import videojs from 'video.js';
import 'video.js/dist/video-js.css';
import {useRoute, useRouter} from 'vue-router';
import VideoApi from "@/apis/VideoApi.js";
import UrlUtil from "@/utils/Url/Url.js";
import IndexHeader from "@/components/IndexHeader.vue";
import dayjs from "dayjs";
import FirstLevelComment from "@/views/videoPlayView/components/FirstLevelComment.vue";
import User from "@/utils/User/User.js"
import {favoriteApi} from "@/apis/favoriteApi.js";
import UserAvatar from "@/components/UserAvatar/UserAvatar.vue";
import HorizonVideoCard from "@/components/horizonVideoCard/horizonVideoCard.vue";
import {followApi} from "@/apis/followApi.js";

const isFollow = ref(false);

const props = defineProps(['fvid'])
const router = useRouter();
const videoPlayer = ref(null);

const videoUrl = ref('')
const videoTitle = ref('');
const videoDescription = ref('');
const videoUploadTime = ref(null);
const videoTags = ref(null)
const videoCommentCount = ref(null)

const videoLiked = ref(false)
const videoLikeNum = ref(0);
const videoFavorited = ref([])
const videoFavoriteNum = ref(0);
const videoIntro = ref(null)

const commentListType = ref('hotest');
const newComment = ref('');
const comments = ref([]);

// 分页pageNum
const pageNum = ref(1)
const pageTotalNum = ref(1)
const totalNum = ref(1)

let player = null;
const route = useRoute();

const recommendVideos = ref([]);

const showFavoritePopup = ref(false);
const selectedCategory = ref('');
const categories = ref([]);
//用户信息
const userInfo = ref({});

const fetchVideoInfo = async () => {
  const fvid = route.params.fvid;

  // 获取视频基本信息
  const res = await VideoApi.getVideoUrl(fvid);
  console.log(res.data.videos[0]);
  const videoInfo = res.data.videos[0];
  videoTitle.value = videoInfo.videoTitle;
  videoUrl.value = videoInfo.url;
  videoUploadTime.value = dayjs(videoInfo.upload_time)
  videoTags.value = videoInfo.videoTags ? videoInfo.videoTags.split(','): null;
  videoCommentCount.value = videoInfo.comment_count;
  videoLikeNum.value = videoInfo.like_count;
  videoFavoriteNum.value = videoInfo.favorite_count;
  videoIntro.value = videoInfo.videoIntro

  userInfo.value = res.data.users[0];
  console.log('获取到的userInfo', userInfo.value);
  // 初始化视频播放器
  nextTick(() => {
    player = videojs(videoPlayer.value, {
      sources: [{
        src: UrlUtil.getFullVideoUrl(videoUrl.value),
        type: 'video/mp4'
      }],
      fluid: true,
      aspectRatio: '16:9',
    });
  });

  //获取视频点赞、收藏状态
  if(User.isLogin()){
    const likeres = await VideoApi.VideoLikeCheck(fvid);
    videoLiked.value = !!likeres.data;
    const favorres = await VideoApi.VideoFavoriteCheck(fvid);
    videoFavorited.value = favorres.data;
    const followres = await followApi.checkFollow(userInfo.value.userid);
    isFollow.value = followres.data;
  }
};

const submitComment = async () => {
  if (!newComment.value.trim()) return;
  try {
    const res = await VideoApi.commentVideo(route.params.fvid,newComment.value)
    console.log('发评论接口',res)
    videoCommentCount.value = videoCommentCount.value+1;
    updateComment(1,10)
  } catch (e) {
    console.log("页面报错",e)
  }

  // comments.value.unshift({ id: Date.now(), content: newComment.value });
  newComment.value = '';
};

// 视频点赞
const toogleVideoLike = async () =>{
  try {
    if (videoLiked.value){
      await VideoApi.VideoUnlike(props.fvid);
      videoLiked.value = false;
      videoLikeNum.value--;
    } else {
      await VideoApi.VideoLike(props.fvid);
      videoLiked.value = true;
      videoLikeNum.value++;
    }
  } catch (e) {
    ElMessage.error('点赞失败')
  }
}
// 视频收藏
const toogleVideoFavorite = async () =>{
  try {
    if (videoFavorited.value.length){
      await favoriteApi.deleteVideoFavorite(props.fvid,videoFavorited.value[0]);
      videoFavorited.value = false;
      videoFavoriteNum.value--;
    } else {
      openPopup();
    }
  } catch (e) {
    ElMessage.error('点赞失败')
  }
}

//获取首页视频
async function fetchVideos() {
  try {
    const res = await VideoApi.fetchAllVideo(15,1);
    recommendVideos.value = res.data.videos;
  } catch (error) {
    console.error('Failed to fetch videos:', error)
  }
}

// 视频收藏请求

// 评论点赞请求

// 评论评论请求

//无限滚动请求
const handleInfiniteScroll = ()=>{
  fetchComment(pageNum.value)
}

//一级评论请求函数
const fetchComment = async (PageNum=1,PageSize=10) => {
  const res = await VideoApi.fetchFirstComments(props.fvid,PageSize,PageNum);
  console.log('评论接口出参',res);
  comments.value= [...comments.value,...res.data.comment_list];
  pageNum.value = pageNum.value+1;
  pageTotalNum.value = res.data.Page_total_size;
  totalNum.value = res.data.comment_total_num;
}

const updateComment = async (PageNum=1,PageSize=10) => {
  const res = await VideoApi.fetchFirstComments(props.fvid,PageSize,PageNum);
  console.log('评论接口出参',res);
  comments.value= res.data.comment_list;
  pageTotalNum.value = res.data.Page_total_size;
  pageNum.value = 1;
}



// 收藏夹相关
const openPopup = () => {
  showFavoritePopup.value = true;
  fetchCategories();
};

const closePopup = () => {
  showFavoritePopup.value = false;
};

const fetchCategories = async () => {
  try {
    const response = await favoriteApi.getCategoryList();
    categories.value = response; // 假设返回的是一个字符串数组
  } catch (error) {
    console.log('触发')
    categories.value = ['默认收藏夹']
  }
  showFavoritePopup.value = true;
};

const addToFavorites = async () => {
  if (!selectedCategory.value) {
    ElMessage.warning('请选择一个分类');
    return;
  }
  try {
    await favoriteApi.addVideoFavorite(props.fvid, selectedCategory.value);
    ElMessage.success('添加成功');
    videoFavorited.value = [selectedCategory.value];
    videoFavoriteNum.value++;
    closePopup();
  } catch (error) {
    ElMessage.error('添加到收藏夹失败:', error.message);
  }
};


// 新增分类相关的状态管理
const isAddingCategory = ref(false);
const newCategory = ref('');
const addCategoryButtonText = ref('新增分类');
// 切换新增分类输入框的显示/隐藏
const toggleAddCategory = () => {
  isAddingCategory.value = !isAddingCategory.value;
  addCategoryButtonText.value = isAddingCategory.value ? '取消' : '新增分类';
  if (isAddingCategory.value) {
    nextTick(() => {
    });
  }
};

// 添加新的分类到 categories 数组中
const addCategory = () => {
  if (newCategory.value.trim() === '') {
    alert('请输入分类名称');
    return;
  }
  categories.value.push(newCategory.value.trim());
  newCategory.value = '';
  toggleAddCategory(); // 关闭新增分类输入框
};
watch(route, (to, from) => {
  router.go(0)
})

const toggleFollow = async () => {
  try {
    if (isFollow.value) {
      // 如果已经关注，则取消关注
      await followApi.deleteFollow(userInfo.value.userid);
      isFollow.value = false;
      ElMessage.success('取消关注成功');
    } else {
      // 如果未关注，则添加关注
      await followApi.addFollow(userInfo.value.userid);
      isFollow.value = true;
      ElMessage.success('关注成功');
    }
  } catch (error) {
    ElMessage.error('操作失败');
    console.error('Error toggling follow:', error);
  }
};

onMounted(() => {
  fetchVideoInfo();
  fetchComment(pageNum.value)
  fetchVideos();


});
onActivated(() => {
  fetchVideoInfo();
  fetchComment(pageNum.value)
  fetchVideos();

});

</script>

<style lang="less" scoped>
.video-play-view {
  min-width: 1100px;
  padding-top: 64px;
  padding-left: 50px;
  padding-right: 50px;
  display: flex;
  align-items: flex-start;
  flex-direction: row;
  font-family: PingFang SC, HarmonyOS_Regular, Helvetica Neue, Microsoft YaHei, sans-serif !important;

  &-right-container{
    flex: 0 0 350px;
    display: flex;
    justify-content: center;
    align-items: flex-start;
    flex-direction: column;
    .user-info-section{
      height: 104px;
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: flex-start;
      user-select: none;

      .user-avatar{
        width: 48px;
        height: 48px;
      }
      .user-info{
        margin-left: 12px;
        flex:1;
        .user-name{
          height: 23px;
          font-size: 16px;
          font-weight: 500;
          color: black;
        }
        .user-intro{
          margin: 2px 0;
          font-size: 14px;

        }
        .actionBtn-section{
          width: 100%;
          .followBtn{
            width: 100%;
            max-width: 200px;
          }
        }
      }
    }

    .recommendVideoSection{
      .recommend-video-box{
        width: 100%;
        height: 80px;
        margin-top: 12px;
      }
    }
  }
  &-left-container{
    flex: 1;
    margin-right: 30px;

    .video-title{
      height: 104px;
      width: 100%;
      display: flex;
      justify-content: center;
      align-items: flex-start;
      flex-direction: column;
      h1{
        font-size:20px;
        font-weight: 500;
        line-height: 28px;
      }

      .video-sub-title{
        height: 24px;
        color: #9499a0;
        margin-top: 6px;
        display: flex;
        flex-direction: row;
        justify-content: flex-start;
        align-items: center;
        &-item{
          margin-right: 20px;
        }
      }
    }
    .tool-bar{
      padding: 16px 0 12px 0;
      display: flex;
      flex-direction: row;
      .tool-bar-item{
        width: 92px;
        margin-right: 16px;
        display: flex;
        align-items: center;
        justify-content: flex-start;
        flex-direction: row;
        i{
          font-size: 28px;
          margin-right: 10px;
        }
      }
      .liked{
        color:rgb(102.2, 177.4, 255) !important;
      }
    }

    .video-tags-box{
      .video-tag{
        margin: 0 10px;
      }
      margin-bottom: 10px;
    }

    .video-intro{
      margin:12px 0 ;
    }
  }
}


.el-divider{
  margin: 0 !important;
}

.video-player {
  width: 100%;
  margin: 0 auto;
}

.video-info {
  margin-top: 20px;
}

.comment-section {
  margin-top: 20px;
  width: 100%;

  .comment-input-section{
    width: 100%;
    display: flex;
    align-items: center;

    .user-avatar{
      width: 48px;
      height: 48px;
      margin: 0 12px;
    }
    .comment-input{
      flex:1;
      padding: 8px;
      height: 60px;
      border-radius: 10px;
    }
  }
  .comment-submit-btn{
    width: 100%;
    display: flex;
    justify-content: flex-end;
    padding-right: 8px;
  }

  .nav-bar{
    display: flex;
    align-items: center;
    height: 28px;
    margin-bottom: 22px;

    .title{
      display: flex;
      align-items: center;

      span{
        margin-left: 10px;
        color: #9499a0;
      }
    }
  }
}

.comment-item {
  margin-top: 10px;
  padding-top: 10px;
  width: 100%;
}
 .none-comment-content{
   width: 100%;
   text-align: center;
   font-size: 14px;
   color: #9499a0;
 }

//
///* 自定义样式 */
//:deep(.el-dialog__header) {
//  padding: 20px;
//  border-bottom: 1px solid #ebeef5;
//}
//
//:deep(.el-dialog__body) {
//  padding: 0 20px;
//}
//
//:deep(.el-dialog__footer) {
//  padding: 10px 20px;
//  text-align: right;
//  border-top: 1px solid #ebeef5;
//}
//
//.category-list {
//  .category-item {
//    display: block;
//    width: 100%;
//    padding: 10px 0;
//    border-bottom: 1px solid #ebeef5;
//    position: relative;
//
//    &:last-child {
//      border-bottom: none;
//    }
//
//    :deep(.el-radio__input) {
//      display: none; // 隐藏默认的单选按钮
//    }
//
//    :deep(.el-radio__label) {
//      width: 100%;
//      padding-left: 20px; // 左侧留出一些空间给自定义的单选图标
//      position: relative;
//
//      &::before {
//        content: '';
//        display: inline-block;
//        width: 16px;
//        height: 16px;
//        border: 1px solid #ccc;
//        border-radius: 50%;
//        vertical-align: middle;
//        margin-right: 10px;
//        position: absolute;
//        left: 0;
//      }
//
//      &::after {
//        display: none;
//        position: absolute;
//        left: 4px;
//        top: 2px;
//        color: #ff9900; // 根据B站风格调整颜色
//      }
//    }
//
//    :deep(.el-radio__input.is-checked + .el-radio__label) {
//      &::after {
//        display: inline-block;
//      }
//    }
//  }
//}
</style>
